package net.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bo.KUtilisateur;
import net.ko.http.objects.KRequest;
import net.technics.ClassTechnics;

public class UrlControl extends LogControl {

	@Override
	public boolean isValid(HttpServletRequest request,
			HttpServletResponse response) {

		boolean result = super.isValid(request, response);
		if (!result)
			return result;
		/*
		 * HttpSession session = request.getSession(); KUtilisateur user =
		 * (KUtilisateur) session.getAttribute("activeUser"); String prefixe =
		 * user.getCompte().getLibelle().substring(0, 3).toLowerCase(); prefixe
		 * = prefixe.replace("Ã©", "e");
		 */

		KUtilisateur user = ClassTechnics.getActiveUser(request);

		String urlUser = getPrefixe(request, user);
		urlUser = urlUser + "Home.do";

		String urlDemande = getUrlDemande(request);

		return urlDemande.startsWith(urlUser);
	}

	public String getUrlDemande(HttpServletRequest request) {
		String urlDemande = request.getRequestURI();
		urlDemande = urlDemande.replace(request.getServletContext().getContextPath() + "/", "");
		return urlDemande;
	}

	public String getPrefixe(HttpServletRequest request, KUtilisateur user) {
		String prefixe = "";
		if (user.getCompte() != null) {
			prefixe = user.getCompte().getLibelle().substring(0, 3).toLowerCase();
			prefixe = prefixe.replace("é", "e");
		}
		return prefixe;
	}

	@Override
	public void onInvalidControl(HttpServletRequest request,
			HttpServletResponse response) {
		KUtilisateur user = ClassTechnics.getActiveUser(request);
		if (user == null) {
			try {
				KRequest.forward("home.do", request, response);
			} catch (ServletException | IOException e) {
				e.printStackTrace();
			}
		} else {
			try {
				KRequest.forward(getPrefixe(request, user) + getUrlDemande(request).substring(3), request, response);
			} catch (ServletException | IOException e) {
				e.printStackTrace();
			}
		}

	}

}
